<?php
namespace App\Services;

use App\Models\Restaurants;
use App\Models\Store;
use App\Models\RestaurantsStatistics;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 *
 * 农家乐服务层
 *
 * @author maqu
 *
 */
class RestaurantsService extends BaseService {

    public function update_statistics($hotels_id,$column ='views'){
        RestaurantsStatistics::where('restaurants_id',$hotels_id)->increment($column);
    }

    /**
     * 获取农家乐列表
     *
     * @param $province
     * @param $lat
     * @param $lon
     * @param $level
     * @param $city
     * @param $country
     * @param $sort_type
     * @param $sort
     * @param $firstrow
     * @param $pagesize
     * @return array
     */
    public function getList($lat,$lon,$province,$city,$country,$sort_type,$sort,$firstrow,$pagesize){

		if($lat=='undefined'){
			$lat = 999;
		}
		if($lon=='undefined'){
			$lon = 999;
		}
		
    //参数
        //【排序】
        //  sort_type 排序方式 price or sales or distance
        //  sort    升降序 asc or desc
        //【位置】
        // country 0-all or 选择的县的regionid
        //【翻页】
        //firsstrow
        //pagesize

        $data = [
            'countries'=>[],
            'restaurants'=>[]
        ];

        //基础
        $query =DB::table('restaurants')
            ->where('if_show',1)
            ->where('closed',0)
            ->where('hidden',0);

        if($province){
            $query->where('province',$province);
        }
        if($city){
            $query->where('city',$city);
        }
//        if($country && $country != '全部'){
//            $query->where('country',$country);
//        }
        if($country == '全部'){
            $country = 0;
        }

        //统计线路数量
        $groupdata = $query->groupBy('country')
            ->select(DB::raw('country,count(*) as num'))
            ->get();

        $total =0;
        $tempdats = [];
        //$data['countries'][]=['item_id'=>0,'item_name'=>'全部','count'=>$total];
        if($groupdata){
            foreach($groupdata as $item){
                $total+=$item->num;
            }
            $data['countries'][]=['item_id'=>0,'item_name'=>'全部','count'=>$total];
            foreach($groupdata as $item){
                $data['countries'][]=['item_id'=>$item->country,'item_name'=>$item->country,'count'=>$item->num];
            }
        }

        unset($total,$groupdata,$query);

        switch($sort_type){
            case 'price':

                $tourdata = $this->getList_orderByPrice($lat,$lon,$province,$city,$country,$sort_type,$sort,$firstrow,$pagesize);

                if($tourdata){
                    foreach($tourdata as  $value){
                        $value->default_image = complete_url( $value->default_image);
                        $value->default_image2 = complete_url( $value->default_image2);
                    }
                    $data['restaurants']=$tourdata;
                }

                break;
            case 'sales':

                $tourdata = $this->getList_orderBySales($lat,$lon,$province,$city,$country,$sort_type,$sort,$firstrow,$pagesize);

                if($tourdata){
                    foreach($tourdata as  $value){
                        $value->default_image = complete_url( $value->default_image);
                        $value->default_image2 = complete_url( $value->default_image2);
                    }
                    $data['restaurants']=$tourdata;
                }

                break;
            case 'views':

                $tourdata = $this->getList_orderByViews($lat,$lon,$province,$city,$country,$sort_type,$sort,$firstrow,$pagesize);

                if($tourdata){
                    foreach($tourdata as  $value){
                        $value->default_image = complete_url( $value->default_image);
                        $value->default_image2 = complete_url( $value->default_image2);
                    }
                    $data['restaurants']=$tourdata;
                }

                break;
            case 'distance':

                $tourdata = $this->getList_orderByDistance($lat,$lon,$province,$city,$country,$sort_type,$sort,$firstrow,$pagesize);

                if($tourdata){
                    foreach($tourdata as  $value){
                        $value->default_image = complete_url( $value->default_image);
                        $value->default_image2 = complete_url( $value->default_image2);
                    }
                    $data['restaurants']=$tourdata;
                }
                break;
            default:
                return $this->failure('未实现');

        }

        return $this->success($data);

    }

    private function getList_orderByPrice($lat,$lon,$province,$city,$country,$sort_type,$sort,$firstrow,$pagesize){

        $query =DB::table('restaurants')
            ->where('if_show',1)
            ->where('closed',0)
            ->where('hidden',0);

        if($province){
            $query->where('province',$province);
        }
        if($city){
            $query->where('city',$city);
        }
        if($country){
            $query->where('country',$country);
        }

        $query->select(DB::raw("round(6378.138*2*asin(sqrt(pow(sin(($lat*pi()/180-latitude*pi()/180)/2),2)+cos($lat*pi()/180)*cos(latitude*pi()/180)* pow(sin( ($lon*pi()/180-longitude*pi()/180)/2),2)))*1000) as distance,
        restaurants_name,short_name,brief,default_image,default_image2,market_price,province,city,country"),'restaurants.restaurants_id');

        $tourdata = $query
            ->orderBy('market_price',$sort)
            ->skip($firstrow)
            ->take($pagesize)
            ->get();

        return $tourdata;

    }

    private function getList_orderBySales($lat,$lon,$province,$city,$country,$sort_type,$sort,$firstrow,$pagesize){
        $query =DB::table('restaurants')
            ->leftJoin('restaurants_statistics','restaurants.restaurants_id','=','restaurants_statistics.restaurants_id')
            ->where('if_show',1)
            ->where('closed',0)
            ->where('hidden',0);

        if($province){
            $query->where('province',$province);
        }
        if($city){
            $query->where('city',$city);
        }
        if($country){
            $query->where('country',$country);
        }

        $query->select(DB::raw("round(6378.138*2*asin(sqrt(pow(sin(($lat*pi()/180-latitude*pi()/180)/2),2)+cos($lat*pi()/180)*cos(latitude*pi()/180)* pow(sin( ($lon*pi()/180-longitude*pi()/180)/2),2)))*1000) as distance,
        restaurants_name,short_name,brief,default_image,default_image2,market_price,province,city,country"),'restaurants.restaurants_id');

        $tourdata = $query
            ->orderBy('hotels_statistics.sales',$sort)
            ->skip($firstrow)
            ->take($pagesize)
            ->get();

        return $tourdata;
    }

    private function getList_orderByViews($lat,$lon,$province,$city,$country,$sort_type,$sort,$firstrow,$pagesize){
        $query =DB::table('restaurants')
            ->leftJoin('restaurants_statistics','restaurants.restaurants_id','=','restaurants_statistics.restaurants_id')
            ->where('if_show',1)
            ->where('closed',0)
            ->where('hidden',0);

        if($province){
            $query->where('province',$province);
        }
        if($city){
            $query->where('city',$city);
        }
        if($country){
            $query->where('country',$country);
        }

        $query->select(DB::raw("round(6378.138*2*asin(sqrt(pow(sin(($lat*pi()/180-latitude*pi()/180)/2),2)+cos($lat*pi()/180)*cos(latitude*pi()/180)* pow(sin( ($lon*pi()/180-longitude*pi()/180)/2),2)))*1000) as distance,
        restaurants_name,short_name,brief,default_image,default_image2,market_price,province,city,country"),'restaurants.restaurants_id');

        $tourdata = $query
            ->orderBy('restaurants_statistics.views',$sort)
            ->skip($firstrow)
            ->take($pagesize)
            ->get();

        return $tourdata;
    }

    private function getList_orderByDistance($lat,$lon,$province,$city,$country,$sort_type,$sort,$firstrow,$pagesize){

        $query =DB::table('restaurants')
            ->where('if_show',1)
            ->where('closed',0)
            ->where('hidden',0);

        if($province){
            $query->where('province',$province);
        }
        if($city){
            $query->where('city',$city);
        }
        if($country){
            $query->where('country',$country);
        }

        $query->select(DB::raw("round(6378.138*2*asin(sqrt(pow(sin(($lat*pi()/180-latitude*pi()/180)/2),2)+cos($lat*pi()/180)*cos(latitude*pi()/180)* pow(sin( ($lon*pi()/180-longitude*pi()/180)/2),2)))*1000) as distance,
        restaurants_name,short_name,brief,default_image,default_image2,market_price,province,city,country"),'restaurants.restaurants_id');

        $tourdata = $query
            ->orderBy('distance',$sort)
            ->skip($firstrow)
            ->take($pagesize)
            ->get();

        return $tourdata;

    }

    /**
     * 获取指定店铺的农家乐列表
     *
     * @param $store_id
     * @param $lat
     * @param $lon
     * @param $firstrow
     * @param $pagesize
     * @return null
     */
    public function getVillagerRestaurantsByStoreId($store_id,$lat,$lon,$firstrow,$pagesize){

		if($lat=='undefined'){
			$lat = 999;
		}
		if($lon=='undefined'){
			$lon = 999;
		}
		
        $query =DB::table('restaurants')
            ->where('store_id',$store_id)
            ->where('if_show',1)
            ->where('closed',0)
            ->where('hidden',0);

        $datas=null;

        if($lat==999 && $lon ==999){
            $query->select(DB::raw("country as distance,
        restaurants_name,short_name,brief,default_image,default_image2,price,market_price,province,city,country"),'restaurants.restaurants_id');

            $datas = $query
                ->orderBy('add_time','desc')
                ->skip($firstrow)
                ->take($pagesize)
                ->get();

        } else {
            $query->select(DB::raw("round(6378.138*2*asin(sqrt(pow(sin(($lat*pi()/180-latitude*pi()/180)/2),2)+cos($lat*pi()/180)*cos(latitude*pi()/180)* pow(sin( ($lon*pi()/180-longitude*pi()/180)/2),2)))*1000) as distance,
        restaurants_name,short_name,brief,default_image,default_image2,price,market_price,province,city,country"),'restaurants.restaurants_id');

            $datas = $query
                ->orderBy('add_time','desc')
                ->orderBy('distance','asc')
                ->skip($firstrow)
                ->take($pagesize)
                ->get();
        }

        if($datas){
            foreach($datas as $d){
                $d->default_image = complete_url($d->default_image);
                $d->default_image2 = complete_url($d->default_image2);
            }
        }

        return $this->success($datas);

    }

    /**
     * 农家乐详情
     *
     * @param $restaurants_id
     * @param $user_id
     * @param bool|false $statics_flg
     * @param bool|true $collect_flg
     * @return array|bool
     */
    public function getRestaurantsDetail($restaurants_id,$user_id,$statics_flg=false,$collect_flg=true){

        //获取数据
        $restaurant =Restaurants::find($restaurants_id);
        if(!$restaurant){
            return false;
        }
        if(!$restaurant->store){
            return false;
        }

        //存在性判断
        if (!$restaurant || $restaurant->closed== 1 || !$restaurant->store || $restaurant->store->state != STORE_STATE_OPENING) {
            return false;
        }

        $data = [
            'store_name'=>'',
            'restaurants_info'=>[
                'base'=>[],     //基本详情
                'albums'=>[]     //相册
            ],
            'phy_store'=>[],    //实体点
            'statics'=>[],      //统计信息
            'collect_status'=>0    //收藏状态
        ];

        $goods_arr = $restaurant->toArray();

        //商品基本信息 商品名，售价，市场价格,图文详情
        $data['restaurants_info']['base'] =$this->prepareRestaurant($goods_arr);

        //商品相册
        $albums = $restaurant->albums()
            ->orderBy('sort_order','asc')->get()->toArray();

        foreach ($albums as $key=>$item){
            if(!empty($item['image_url'])){
                $albums[$key]['image_url'] = complete_url($item['image_url']);
            }
            if(!empty($item['thumbnail'])){
                $albums[$key]['thumbnail'] = complete_url($item['thumbnail']);
            }
        }
        $data['restaurants_info']['albums']=$albums;

        //店铺
        $phy_store = $restaurant->phystore;
        if($phy_store){
            $data['phy_store']=[
                'phy_store_id'=>$phy_store->phy_store_id,
                'phy_store_name'=>$phy_store->phy_store_name,
                'region_name'=>$phy_store->region_name,
                'address'=>$phy_store->address,
                'tel'=>$phy_store->tel,
                'longitude'=>$phy_store->longitude,
                'latitude'=>$phy_store->latitude
            ];
        }
        $store_id = $restaurant->store_id;
        $store_info = Store::find($store_id);
        $data['store_name'] = $store_info->store_name;

        //统计    已售 收藏 好评 评论数量
        if($statics_flg){

            $statistics = $restaurant->statics;

            if($statistics){
                $data['statics']=$statistics->toArray();
                unset($data['statics']['restaurants_id']);
            } else {
                $data['statics']=['views'=>0,'collects'=>0,'carts'=>0,'orders'=>0,'sales'=>0,'comments'=>0];
            }

        }

        //收藏状态
        if($collect_flg && $user_id){

            $count= DB::table('collect')
                ->where('user_id',$user_id)
                ->where('type','restaurant')
                ->where('item_id',$restaurants_id)->count();

            $data['collect_status']=$count?1:0;

        }

        return $data;

    }

    /**
     * @param $restaurant
     * @return mixed
     */
    public function prepareRestaurant($restaurant){

        //商品基本信息 商品名，售价，市场价格,图文详情
        unset($restaurant['store']);

        $html =complete_html(config('maqu.STATIC_RESOURCE_URL'),$restaurant['restaurants_name'],$restaurant['description']);
        $restaurant['description']=$html;

        $html =complete_html(config('maqu.STATIC_RESOURCE_URL'),$restaurant['restaurants_name'],$restaurant['intro1']);
        $restaurant['intro1']=$html;

        $html =complete_html(config('maqu.STATIC_RESOURCE_URL'),$restaurant['restaurants_name'],$restaurant['intro2']);
        $restaurant['intro2']=$html;

        $html =complete_html(config('maqu.STATIC_RESOURCE_URL'),$restaurant['restaurants_name'],$restaurant['intro3']);
        $restaurant['intro3']=$html;

        $html =complete_html(config('maqu.STATIC_RESOURCE_URL'),$restaurant['restaurants_name'],$restaurant['intro4']);
        $restaurant['intro4']=$html;

        unset($html);

        if(!empty($restaurant['default_image'])){
            $restaurant['default_image'] = complete_url($restaurant['default_image']);
        }

        if(!empty($restaurant['default_image2'])){
            $restaurant['default_image2'] = complete_url($restaurant['default_image2']);
        }

        return $restaurant;

    }

//    /**
//     * 获取线路的评价列表
//     * @param $tour_id
//     * @param $firstrow
//     * @param $pagesize
//     * @return array
//     */
//    public function getComments($tour_id,$firstrow,$pagesize){
//
//        $tour = Tour::find($tour_id);
//
//        if(!$tour){
//            return $this->failure('该线路不存在');
//        }
//
//        $comments = DB::table('tour_order_evaluation')
//            ->where('tour_id',$tour_id)
//            ->skip($firstrow)
//            ->take($pagesize)
//            ->get();
//
//        return $this->success($comments);
//
//    }

}